package com.carbon.carbonmanager.controller;

import com.carbon.carbonmanager.unit.Response;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
public class UploadController {
    //图片存放的相对于项目的相对位置
    final static String PIC_PATH = "static/img/";
    final static String DEL_PATH = "src/main/resources/static/";
    /**
     * 单文件上传改造
     */
    public String uploadsingle(MultipartFile file, HttpServletRequest request){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //生成日期格式
        String datePrefix = dateFormat.format(new Date()); //生成当前日期作为前缀
        String savePath = "src/main/resources/" + PIC_PATH; // 存储路径

        File folder = new File(savePath+datePrefix); //生成带当前日期的文件路径

        if(!folder.isDirectory()){
            folder.mkdirs();
        }

        //String randomName = multiRequest.getFile("image").getOriginalFilename(); //获取图片名
        String randomName = file.getOriginalFilename();
        //生成随机数确保唯一性，并加上图片后缀
        String saveName = UUID.randomUUID().toString() + randomName.substring(randomName.lastIndexOf("."),randomName.length());
        String absolutePath = folder.getAbsolutePath(); //转换成绝对路径

        try {
            File fileToSave = new File(absolutePath + File.separator + saveName);
            //multiRequest.getFile("image").transferTo(fileToSave); //图片存储到服务端
            file.transferTo(fileToSave);//图片存储到服务端
            String returnPath = request.getScheme() + "://"
                    + request.getServerName()+":"+request.getServerPort()
                    + "/img/" + datePrefix +"/"+ saveName;

            return  returnPath;

        }catch (Exception e){
            e.printStackTrace();
        }
        return "上传失败";
    }


    /**
     * 多文件
     * 图片上传
     *
     */
    @PostMapping("/uploadpics")
    public Response uploadPicMultipart(MultipartHttpServletRequest multiRequest, HttpServletRequest request){
        List<String> list = new ArrayList<String>();
        List<MultipartFile> fileList = multiRequest.getFiles("image");
        for(MultipartFile file : fileList){
            String url = uploadsingle(file,request);
            list.add(url);
        }
        return new Response(200,"上传成功",list);
    }
}
